# -*- coding: utf-8 -*-
import os
import re
import sys
from MyEncoder import MyEncoder
reload(sys)

sys.path.append("./common")
sys.path.append("./iotprobe")
sys.path.append(os.getcwd())
sys.setdefaultencoding('utf-8')
# 此行一定放在logging之前
module_name = "huey_probe"
os.environ['LOG_FILE_NAME'] = module_name
import ty_log as logging


import json




re_mac = re.compile('([a-f0-9]{2}[-:]){5}[a-f0-9]{2}', re.I)



class device:
    def __init__(self, ip=None, mac=None, taxonomy="O", vendor=None, model=None, id=None, gwip='', gwmac='', gwt='',
                 probedetail='', hops=None, os=None, aiotprobe=None, ports=None, protocols=None):
        self.ip = ip;
        self.mac = mac;
        self.taxonomy = taxonomy;
        self.vendor = vendor;
        self.model = model;
        self.id = id;
        self.gwip = gwip;
        self.gwmac = gwmac;
        self.gwt = gwt;
        self.probedetail = probedetail;
        self.hops = hops;
        self.os = os;
        self.aiotprobe = aiotprobe
        self.ports = ports
        self.protocols = protocols


def conver_ip2mac(ip):
    '''
    把IP转成MAC的形式，当做唯一值使用
    :param ip:
    :return:
    '''
    s = ip.replace('.', "")
    while len(s) < 12:
        s += 'F'

    lst = []
    for i in range(0, len(s), 2):
        lst.append(s[i:i + 2])

    moke_mac = ':'.join(lst)

    return moke_mac


def fill_osinfo(dev, os_info):
    if os_info:
        if int(os_info[0]['accuracy']) >= 96:
            if 'router' in os_info[0]['osclass'][0]['type']:
                dev.taxonomy = 'NR'
                dev.vendor = os_info[0]['osclass'][0]['vendor']
                dev.model = os_info[0]['osclass'][0]['osgen']
            elif 'general purpose' == os_info[0]['osclass'][0]['type']:
                dev.taxonomy = 'PC'
                dev.vendor = os_info[0]['osclass'][0]['vendor']
                dev.model = os_info[0]['osclass'][0]['osgen']
            elif 'phone' == os_info[0]['osclass'][0]['type']:
                dev.taxonomy = 'PHONE'
                dev.vendor = os_info[0]['osclass'][0]['osfamily']
                dev.model = os_info[0]['osclass'][0]['osgen']
            elif 'switch' == os_info[0]['osclass'][0]['type']:
                dev.taxonomy = 'NS'
                dev.vendor = os_info[0]['osclass'][0]['vendor']
                dev.model = os_info[0]['osclass'][0]['osfamily']

def do_log_for_dev(dev):
    d = {}
    if dev:
        '''
        if not dev.hops:
            ip = IP(dev.ip)
            if ip.iptype() == 'PRIVATE':
                dev.hops = 2
            elif ip.iptype() == 'PUBLIC':
                dev.hops = 10
        '''
        d['asset_ip'] = dev.ip
        d['asset_mac'] = dev.mac.upper()
        d['asset_type'] = dev.taxonomy
        d['brand'] = dev.vendor
        d['model'] = dev.model
        d['id'] = dev.id
        d['detail'] = dev.probedetail
        d['hops'] = dev.hops
        d['os'] = dev.os
        d['ports'] = dev.ports
        d['protocols'] = dev.protocols
        d['interface'] = ''
        if dev.aiotprobe:
            d['aiotprobe'] = dev.aiotprobe
        # send2syslog 设置成TRUE，就是说明是单条发送
        logging.info(json.dumps(d), send2syslog=True)

    return d

def do_log_for_bt(dev):
    #maclist = ""
    d = {}
    if dev:
        '''
        if not dev.hops:
            ip = IP(dev.ip)
            if ip.iptype() == 'PRIVATE':
                dev.hops = 2
            elif ip.iptype() == 'PUBLIC':
                dev.hops = 10
        '''

        d['asset_ip'] = dev['MAC'].upper()
        d['asset_mac'] = dev['MAC'].upper()
        #maclist = maclist + d['asset_mac']
        d['asset_type'] = dev['device_type']
        #d['brand'] = dev['provider']
        d['model'] = ""
        d['hops'] = 2
        #d['id'] = dev['status']
        d['detail'] = dev['deviceName']
        d['pro'] = dev['pro']
        d['status'] = dev['status']
        d['ports'] = dev['port']
        d['protocols'] = dev['protocol']
        d['interface'] = 'Classic Blue'
        #d['aiotprobe'] = dev['port']

        '''
        if dev.aiotprobe:
            d['aiotprobe'] = dev.aiotprobe
        '''
        # send2syslog 设置成TRUE，就是说明是单条发送
        logging.info(json.dumps(d).encode('utf-8'), send2syslog=True)
    #print maclist
    return d

def do_log_for_ble(dev):
    d = {}
    aa={}
    if dev:
        '''
        if not dev.hops:
            ip = IP(dev.ip)
            if ip.iptype() == 'PRIVATE':
                dev.hops = 2
            elif ip.iptype() == 'PUBLIC':
                dev.hops = 10
        '''
        d['hops'] = 2
        d['asset_ip'] = dev['MAC'].upper()
        d['asset_mac'] = dev['MAC'].upper()
        d['asset_type'] = dev['MAC type']
        d['rssi'] = dev['RSSI']
        d['services'] = dev['service']
        d['Flags'] = dev['Flags']
        d['detail'] = dev['devicename']
        #d['Manufac'] = dev['Manufac']
        #d['os'] = dev.os
        #d['ports'] = dev.ports
        #d['protocols'] = dev.protocols
        d['interface'] = 'Ble'
        aa['bleinfo'] =d
        '''
        if dev.aiotprobe:
            d['aiotprobe'] = dev.aiotprobe
        '''
        # send2syslog 设置成TRUE，就是说明是单条发送
        logging.info(json.dumps(aa), send2syslog=True)

    return aa
def do_log_for_blueleak(leaklist):
    blueleak = {}
    blueleak['blueleak'] = leaklist
    logging.info(json.dumps(blueleak), send2syslog=True)
def do_log_for_wifileak(wifileaklist):
    wifileak ={}
    wifileak['wifileak'] = wifileaklist
    logging.info(json.dumps(wifileak), send2syslog=True)


def get_macbyip(ip_src):
    os.popen('ping -nq -c 1 -W 2 {} > /dev/null'.format(ip_src))
    result = os.popen('arp -an {}'.format(ip_src))
    result = re_mac.search(result.read())
    return result.group() if result else ''


if __name__ == '__main__':
    # probe(['192.168.1.5'])
    if len(sys.argv) != 2:
        print "USAGE : python probe.py from to "
        sys.exit(1)


elif "probe.probe" == __name__:
    logging.info("{} started.".format(__name__))
